<?php
/**
 * 登录操作
 * @author wangtao
 * @version 2011.05.20
 */


function index()
{
	print_r($_GET);
}

/**
 * QQ登录后跳转页面，执行绑定相关操作
 */
function qq()
{
	if (empty($_REQUEST['openid']) || empty($_REQUEST['timestamp']) || empty($_REQUEST['oauth_signature']) ||
	empty($_REQUEST['oauth_token']) || empty($_REQUEST['oauth_vericode']))
	{
		die('缺少参数！');
	}

	if (!isValidOpenid($_REQUEST['openid'], $_REQUEST['timestamp'], $_REQUEST['oauth_signature']))
	{
	    //demo对错误简单处理
	    echo '###invalid openid\n';
	    echo 'sig:'.$_REQUEST['oauth_signature'].'\n';
	    exit;
	}
	
	$accessStr = getAccessToken($_SESSION['appid'], $_SESSION['appkey'], 
	$_REQUEST['oauth_token'], $_SESSION['secret'], $_REQUEST['oauth_vericode']);
	$result = array();
	parse_str($accessStr, $result);
	
	if (isset($result['error_code']))
	{
	    echo 'error_code = '.$result['error_code'];
   		exit;
	}
	
	if (!isValidOpenid($result['openid'], $result['timestamp'], $result['oauth_signature']))
	{
	    //demo对错误简单处理
    	echo '@@@invalid openid';
   		echo 'sig:' . $result['oauth_signature'] . '\n';
    	exit;
	}
	
	$_SESSION['token']   = $result['oauth_token'];
	$_SESSION['secret']  = $result['oauth_token_secret']; 
	$_SESSION['openid']  = $result['openid'];

	$uid = isValidUid($_SESSION['openid']);

	if ($uid)
	{
		$_SESSION['uid'] = $uid;
		print_r($_SESSION);
	}
	else
	{
		bindUser();
	}

}

/**
 * 跳转到登录页面
 */
function toQqLogin()
{
	redirectToLogin($_SESSION['appid'], $_SESSION['appkey'], $_SESSION['callback']);
}

/**
 * 绑定一个新账号
 */
function bindUserAct()
{
	$uid = $_SESSION['openid'];
	$_SESSION['uid'] = $uid;
	$username = $_POST['userName'];
	bindingUser($uid, $username);
}

function bindUserEr()
{
}

/**
 * 绑定账号页面
 */
function bindUser()
{
	$userInfo = getUserInfo($_SESSION['appid'], $_SESSION["appkey"], $_SESSION["token"], $_SESSION["secret"], 
	$_SESSION["openid"]);
	$userInfo = json_decode($userInfo);
	$nickname = $userInfo->nickname;
	$_SESSION['nickname'] = $nickname;
	#初始化模板
	$views = new smasrty();
	$views->assign('nickname', $nickname);
	$views->display('bindUser.html');
}
